//
//  SignInfoViewController.m
//  MemberProject
//
//  Created by MAC OS X on 15/4/7.
//  Copyright (c) 2015年 MAC OS X. All rights reserved.
//

#import "SignInfoViewController.h"
#import "CityFileManager.h"
#import "IQKeyboardManager.h"
@interface SignInfoViewController ()
{
    NSMutableArray *pArr;
    NSMutableArray *cArr;
    NSMutableArray *dArr;
    
    
    NSMutableArray *provinces;
    NSMutableArray *cities;
    NSMutableArray *areas;
    
    
    NSMutableArray *yearArr;
    NSMutableArray *monthArr;
    NSMutableArray *dayArr;
    
}
@end

@implementation SignInfoViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    [self setupNavigation];
    [self setupData];
    [self setupValue];
    if (self.isDetailAddress) {
        self.detailTextField.hidden = NO;
    }else
        self.detailTextField.hidden = YES;
    
}
-(void)viewWillAppear:(BOOL)animated
{
    [IQKeyboardManager sharedManager].enableAutoToolbar = YES;
    [IQKeyboardManager sharedManager].enable = YES;
}

-(void)setupData
{
    
    
    pArr = [NSMutableArray new];
    cArr = [NSMutableArray new];
    dArr = [NSMutableArray new];
    
    provinces = [NSMutableArray new];
    cities = [NSMutableArray new];
    areas = [NSMutableArray new];
}
#pragma mark 日期
-(void)setupDate
{
    yearArr = [NSMutableArray new];
    monthArr = [NSMutableArray new];
    dayArr = [NSMutableArray new];
    
    NSDate *nowDate = [NSDate date];
    NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
    [formatter setDateFormat:@"yyyy"];
    NSString *yearStr = [formatter stringFromDate:nowDate];
    
    for (int year=1900; year<=yearStr.intValue; year++) {
        [yearArr addObject:[NSString stringWithFormat:@"%d",year]];
    }
    for (int month =1; month<13; month++) {
        if (month<10) {
            [monthArr addObject:[NSString stringWithFormat:@"0%d",month]];
        }
        else [monthArr addObject:[NSString stringWithFormat:@"%d",month]];
    }
    for (int day=1; day<32; day++) {
        if (day<10) {
            [dayArr addObject:[NSString stringWithFormat:@"0%d",day]];
        }else
        [dayArr addObject:[NSString stringWithFormat:@"%d",day]];
    }
    
    [self.pickerView selectRow:100 inComponent:0 animated:NO];
}
#pragma mark 三项选择
-(void)setupDataThreeArea
{
//    NSString *jsonpath=[[NSBundle mainBundle]pathForResource:@"city" ofType:@"json"];
//    NSData *data=[NSData dataWithContentsOfFile:jsonpath];
//    NSError* error;
//    NSDictionary* json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
//    NSArray *arr1 = json[@"citylist"];
    NSArray *cityFileArr = [[CityFileManager sharedManager]getLocalLog:CityFileType];
    void (^setupBlock)(NSArray *) = ^(NSArray *cityArr) {
        
        for (int i=0; i<cityArr.count; i++) {
            
            NSDictionary *dic1 = cityArr[i];
            NSString *pStr =[NSString stringWithFormat:@"%@-%@",dic1[@"n"],dic1[@"c"]];
            [provinces addObject:pStr];
            NSArray *arr2 = dic1[@"child"];
            
            NSMutableArray *cityResultArr = [NSMutableArray new];
            NSMutableArray *areaResulitArr = [NSMutableArray new];
            //
            for (int j=0; j<arr2.count; j++) {
                //
                NSDictionary *dic2 = arr2[j];
                NSString *cStr =[NSString stringWithFormat:@"%@-%@",dic2[@"n"],dic2[@"c"]] ;
                [cityResultArr addObject:cStr];
                NSArray *arr3 = dic2[@"child"];
                
                NSMutableArray *dResultArr = [NSMutableArray new];
                for (int k=0; k<arr3.count; k++) {
                    NSDictionary *dic3 = arr3[k];
                    NSString *dStr = [NSString stringWithFormat:@"%@-%@",dic3[@"n"],dic3[@"c"]];
                    [dResultArr addObject:dStr];
                    
                }
                [areaResulitArr addObject:dResultArr];
            }
            [dArr addObject:areaResulitArr];
            [cArr addObject:cityResultArr];
            
        }
        
        [cities addObjectsFromArray:cArr[0]];
        
        
        if (cityArr) {
            [self.pickerView reloadAllComponents];
        }
    };
    
    
    if (cityFileArr&&cityFileArr.count>0) {
        setupBlock(cityFileArr);
    }else
    {
        [SVProgressHUD showWithStatus:@"正在加载地区" maskType:SVProgressHUDMaskTypeBlack];
        
        [[CityFileManager sharedManager]getCityFile:^(id result) {
            [SVProgressHUD dismiss];
            if (result) {
                
                setupBlock(result);
                
            }else
            {
                [SVProgressHUD showErrorWithStatus:@"加载失败"];
            }
            
        } andDefault:^{
            [SVProgressHUD showErrorWithStatus:@"加载失败"];
            
        }];
    }
    
    
}
-(void)setupValue
{
    switch (self.pickViewStyle) {
        case PickViewAeraThreeChoice:
        {
            [self setupDataThreeArea];
        }
            break;
        case PickViewAeraTwoChoice:
        {
            [self setupDataThreeArea];
        }
            break;
        case PickViewDateThreeChoice:
        {
            [self setupDate];
        }
            break;

    }
}
-(void)setupNavigation
{
    UIButton *finishBtn = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 50, 25)];
    [finishBtn setTitle:@"完成" forState:0];
    finishBtn.titleLabel.textAlignment = NSTextAlignmentCenter;
    [finishBtn setTitleColor:[UIColor whiteColor] forState:0];
    [finishBtn addTarget:self action:@selector(finishOpera) forControlEvents:64];
    self.navigationItem.rightBarButtonItem =[[UIBarButtonItem alloc]initWithCustomView:finishBtn];
    
//    [self addBack];
    
    
    NSString *titleStr= @"";
    switch (self.pickViewStyle) {
        case PickViewAeraThreeChoice:
        {
            titleStr = @"选择地区";
        }
            break;
        case PickViewAeraTwoChoice:
        {
            titleStr = @"选择籍贯";
        }
            break;
        case PickViewDateThreeChoice:
        {
            titleStr = @"选择日期";
        }
            break;
            
    }
//    [self titleWithLabel:titleStr andColor:nil];
    self.title = titleStr;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
//选择
-(NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView{
    switch (self.pickViewStyle) {
        case PickViewAeraThreeChoice:
        {
            return 3;
        }
            break;
        case PickViewAeraTwoChoice:
        {
            return 2;
        }
            break;
        case PickViewDateThreeChoice:
        {
            return 3;
        }
            break;
            
    }
    return 0;
}
-(NSInteger) pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component{
    switch (self.pickViewStyle) {
        case PickViewAeraThreeChoice:
        case PickViewAeraTwoChoice:
        {
            //地区两项选择
            switch (component) {
                case 0:
                {
                    return provinces.count;
                }
                    break;
                case 1:
                {
                    return cities.count;
                }
                    break;
                case 2:
                {
                    return areas.count;
                    
                }
                    break;
                    
            }
        }
            break;
        case PickViewDateThreeChoice:
        {
            //日期
            switch (component) {
                case 0:
                {
                   return  yearArr.count;
                }
                    break;
                case 1:
                {
                    return  monthArr.count;
                }
                    break;
                case 2:
                {
                    return  dayArr.count;
                }
                    break;

            }
        }
            break;
            
    }
    
    
    
    
    return 3;
}
-(UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view
{
    
    UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 80, 20)];
    label.textAlignment = NSTextAlignmentCenter;
    [label setTextColor:[UIColor blackColor]];
    NSString *labelText= @"3";
    switch (self.pickViewStyle) {
        case PickViewAeraThreeChoice:
        case PickViewAeraTwoChoice:
        {
            //地区两项选择
            switch (component) {
                case 0:
                {
                    NSString *provinceStr = provinces[row];
                    NSArray *arr =[provinceStr componentsSeparatedByString:@"-"];
                    labelText = arr[0];
                }
                    break;
                case 1:
                {
                    NSString *cityStr = cities[row];
                    NSArray *arr =[cityStr componentsSeparatedByString:@"-"];
                    labelText = arr[0];
                }
                    break;
                case 2:
                {
                    NSString *areaStr = areas[row];
                    NSArray *arr =[areaStr componentsSeparatedByString:@"-"];
                    labelText = arr[0];
                }
                    break;
                    
            }
        }
            break;
        case PickViewDateThreeChoice:
        {
            //日期
            switch (component) {
                case 0:
                {
                    labelText =  yearArr[row];
                }
                    break;
                case 1:
                {
                    labelText =  monthArr[row];
                }
                    break;
                case 2:
                {
                    labelText =  dayArr[row];
                }
                    break;
                    
            }
        }
            break;
            
    }
    label.text = labelText;
    label.adjustsFontSizeToFitWidth = YES;
    return label;
}
//-(NSString*) pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component{
//    NSString *str = ;
//
//    return @"f";
//}
-(void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
//     dispatch_queue_t scrollQueue = dispatch_queue_create("scroll", DISPATCH_QUEUE_CONCURRENT);
//    dispatch_async(scrollQueue, ^{
    
        switch (self.pickViewStyle) {
            case PickViewAeraThreeChoice:
            {
                [self scrollThreeArea:component];
            }
                break;
            case PickViewAeraTwoChoice:
                [self scrollTwoArea:component];
                break;
            case PickViewDateThreeChoice:
                break;
                
        }
//    });
    
    
    
    
    
    
}
-(void)scrollTwoArea:(NSInteger)component
{
    NSInteger firstComponent = [self.pickerView selectedRowInComponent:0];
    if (component==0)
    {
        NSArray *arr1 = cArr[firstComponent];
        
        if (arr1.count>0) {
            [cities setArray: arr1];
            [self.pickerView selectRow:0 inComponent:1 animated:YES];
        }else
        {
            [cities removeAllObjects];
        }
        [self.pickerView reloadAllComponents];
    }
}
-(void)scrollThreeArea:(NSInteger)component
{
    NSInteger firstComponent = [self.pickerView selectedRowInComponent:0];
    NSInteger secondComponent = [self.pickerView selectedRowInComponent:1];
    if (component==0)
    {
        NSArray *arr1 = cArr[firstComponent];
        if (arr1.count>0) {
            [cities setArray: arr1];
            [self.pickerView selectRow:0 inComponent:1 animated:YES];
        }else
        {
            [cities removeAllObjects];
            
        }
        NSArray *arr2 = dArr[firstComponent];
        [self.pickerView selectRow:0 inComponent:1 animated:YES];
        if (arr2.count>0) {
            NSArray *arr3 = arr2[0];
            if (arr3.count>0) {
                [self.pickerView selectRow:0 inComponent:2 animated:YES];
                [areas setArray: arr3];
            }else
            {
                [areas removeAllObjects];
            }
        }else
        {
            [areas removeAllObjects];
        }
        [self.pickerView reloadAllComponents];
        
    }else if (component==1)
    {
        //        NSArray *arr = dArr
        NSArray *arr1 = dArr[firstComponent];
        if (arr1.count>0) {
            NSArray *arr2 = arr1[secondComponent];
            if (arr2.count>0) {
                [areas setArray: arr2];
            }else
            {
                [areas removeAllObjects];
            }
        }
        [self.pickerView reloadAllComponents];
    }
}
-(void)finishDateEdit:(finishDateBlock)block
{
    self.dateBlock = block;
}

-(void)finishPlaceEdit:(finishPlaceBlock)block
{
    self.placeBlock = block;
}
-(void)finishOpera
{
    if (self.isDetailAddress) {
        if ([self.detailTextField.text isEqualToString:@""]) {
            [SVProgressHUD showErrorWithStatus:@"请填入具体地点" maskType:SVProgressHUDMaskTypeBlack];
            return;
        }
//            else
//        {
//            [self.navigationController popViewControllerAnimated:YES];
//            self.dateBlock(self.detailTextField.text);
//            return;
//        }
//        
    }
    
    NSInteger firstComponent = [self.pickerView selectedRowInComponent:0];
    NSInteger secondComponent = [self.pickerView selectedRowInComponent:1];
//    NSInteger thirdComponent =[self.pickerView selectedRowInComponent:2];

    NSString *finnalStr = @"";
    NSString *codeStr = @"";
    switch (self.pickViewStyle) {
        case PickViewAeraThreeChoice:
            case PickViewAeraTwoChoice:
        {
            NSArray *dataArr = @[provinces,cities,areas];
            for (int i=0; i<dataArr.count; i++) {
                NSArray *arr = dataArr[i];
                if (arr.count>0) {
                    NSInteger component =[self.pickerView selectedRowInComponent:i];
                    NSString *Str =arr[component];
                    
                    NSArray *strArr = [Str componentsSeparatedByString:@"-"];
                    codeStr = [strArr lastObject];
                    if (i==0) {
                        finnalStr =  [finnalStr stringByAppendingString:[NSString stringWithFormat:@"%@",strArr[0]]];
                    }else
                    {
                        finnalStr =  [finnalStr stringByAppendingString:[NSString stringWithFormat:@"%@",strArr[0]]];
                    }
                    
                }
            }
        }
            finnalStr = [finnalStr stringByAppendingString:self.detailTextField.text];
                        self.placeBlock(finnalStr,codeStr);
            break;
            case PickViewDateThreeChoice:
        {
            NSString *formatStr = [NSString stringWithFormat:@"%@-%@-%@",yearArr[firstComponent],monthArr[secondComponent],dayArr[[self.pickerView selectedRowInComponent:2]]];
            if ([Utils validataDate:formatStr]) {
                finnalStr = [NSString stringWithFormat:@"%@-%@-%@",yearArr[firstComponent],monthArr[secondComponent],dayArr[[self.pickerView selectedRowInComponent:2]]];
                 self.dateBlock(finnalStr);
                break;
            }else
            {
                [SVProgressHUD showErrorWithStatus:@"日期格式错误" maskType:SVProgressHUDMaskTypeBlack];
                return;
            }
            
        }
            
            
    }
    
    
    [self.navigationController popViewControllerAnimated:YES];
   
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
